<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑JSA模板' : '创建JSA模板'"
    width="90%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="jsa-template-form"
    >
      <!-- 基本信息 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-title">
            <el-icon><Document /></el-icon>
            <span>基本信息</span>
          </div>
        </template>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作业类型" prop="jobType">
              <el-input v-model="formData.jobType" placeholder="请输入作业类型" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- JSA分析表 -->
      <el-card class="form-section" shadow="never">
        <template #header>
          <div class="section-title">
            <el-icon><List /></el-icon>
            <span>JSA分析表</span>
          </div>
        </template>
        <JSATemplateTableForm v-model="formData" />
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Delete, Plus, Document, List, Warning, Lock, Connection } from '@element-plus/icons-vue'
import JSATemplateTableForm from './JSATemplateTableForm.vue'
import { useJSATemplateStore } from '@/stores/jsTemplate'
import type { JSATemplate, JSATemplateForm } from '@/types'

interface Props {
  modelValue: boolean
  template?: JSATemplate
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const isEdit = computed(() => !!props.template)

// 表单数据
const formData = ref<JSATemplateForm>({
  name: '',
  jobType: '',
  workSteps: [],
  hazards: [],
  controlMeasures: [],
  workStepHazards: [],
  hazardControls: []
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' }
  ],
  jobType: [
    { required: true, message: '请输入作业类型', trigger: 'blur' }
  ]
}

// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    jobType: '',
    workSteps: [],
    hazards: [],
    controlMeasures: [],
    workStepHazards: [],
    hazardControls: []
  }
  formRef.value?.clearValidate()
}

// 监听模板变化，初始化表单数据
watch(() => props.template, (template) => {
  if (template) {
    formData.value = {
      name: template.name,
      jobType: template.jobType,
      workSteps: template.workSteps.map(step => ({
        stepName: step.stepName
      })),
      hazards: template.hazards.map(hazard => ({
        hazardName: hazard.hazardName
      })),
      controlMeasures: template.controlMeasures.map(measure => ({
        measureName: measure.measureName
      })),
      workStepHazards: (template.workStepHazards || []).map(relation => ({
        workStepSequence: relation.workStep?.sequence || 0,
        hazardName: relation.hazard?.hazardName || ''
      })),
      hazardControls: (template.hazardControls || []).map(relation => ({
        hazardName: relation.hazard?.hazardName || '',
        controlMeasureName: relation.controlMeasure?.measureName || ''
      }))
    }
  } else {
    resetForm()
  }
}, { immediate: true })



// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 调用store的方法
    const store = useJSATemplateStore()
    if (isEdit.value) {
      await store.updateTemplate(props.template!.id, formData.value)
    } else {
      await store.createTemplate(formData.value)
    }
    
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
}
</script>

<style lang="scss" scoped>
.jsa-template-form {
  .form-section {
    margin-bottom: 20px;
    
    .section-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 500;
      
      .el-button {
        margin-left: auto;
      }
    }
  }
  
  .steps-container, .hazards-container, .measures-container {
    .step-item, .hazard-item, .measure-item {
      border: 1px solid #e4e7ed;
      border-radius: 6px;
      padding: 16px;
      margin-bottom: 12px;
      background: #fafafa;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .step-header, .hazard-header, .measure-header {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 12px;
        
        .step-number {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          background: #409eff;
          color: white;
          border-radius: 50%;
          font-size: 12px;
          font-weight: 500;
        }
        
        .step-name, .hazard-name, .measure-name {
          flex: 1;
        }
        
        .risk-level, .measure-category {
          width: 120px;
        }
      }
      
      .step-description, .hazard-description, .measure-description {
        width: 100%;
      }
    }
  }
  
  .relations-container {
    .relation-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px;
      border: 1px solid #e4e7ed;
      border-radius: 6px;
      margin-bottom: 12px;
      background: #f9f9f9;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .relation-select {
        flex: 1;
      }
      
      .relation-arrow {
        color: #409eff;
        font-weight: bold;
        font-size: 16px;
      }
    }
  }
}

.dialog-footer {
  text-align: right;
}
</style>
